import fullscreen from 'screenfull'
import { onBeforeUnmount, onMounted, ref, toValue, watch } from 'vue'
import type { MaybeRefOrGetter } from 'vue'

function useFullscreen(el: MaybeRefOrGetter<Element | HTMLElement | null>) {
  const isFullscreen = ref(false)
  const fullscreenChangeHandler = () => {
    isFullscreen.value = !isFullscreen.value
  }

  const toggleMode = ref(() => {})

  watch(
    () => toValue(el),
    () => {
      const element = toValue(el)
      toggleMode.value = () => {
        const enabled = fullscreen.isEnabled
        if (enabled && element) {
          fullscreen.toggle(element)
        }
      }
    },
  )

  onMounted(() => {
    fullscreen.on('change', fullscreenChangeHandler)
  })
  onBeforeUnmount(() => {
    fullscreen.off('change', fullscreenChangeHandler)
  })

  return {
    isFullscreen,
    toggleMode,
  }
}

export default useFullscreen
